﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.DAL.CustomerManage;
using MINERP.DAL;
using System.Data;
using MINERP.COM;
using MINERP.MODEL.NewProject;
using MINERP.BLL.Common;

namespace MINERP.BLL.CustomerManage
{
    public class OrderInfoBLL
    {
        //参数
        private OrderProductDAL dll = new OrderProductDAL();

        #region 获取产品的总量(在某种状态下)
        /// <summary>
        /// 获取产品的总量(在某种状态下)
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public int GetOrderInfoNum(int status)
        {
            try
            {
                return dll.GetOrderInfoNum(status);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取指定范围的产品
        /// <summary>
        /// 获取指定范围的产品
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public List<OrderProductUser> GetOrderInfo(int start, int end, int status)
        {
            try
            {
                List<orderInfo> orderInfos = dll.GetOrderProduct(start, end, status);
                List<OrderProductUser> products = OrderInfoChange(orderInfos);
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 按时间范围获取产品
        /// <summary>
        /// 按时间范围获取产品
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public List<OrderProductUser> GetOrderInfoByTime(DateTime start, DateTime end, int status)
        {
            try
            {
                List<Tb_OrderBag> orders = dll.GetOrderProductByTime(start, end, status);
                List<orderInfo> orderinfos = new List<orderInfo>();
                if (status == -1)
                {
                    foreach (Tb_OrderBag order in orders)
                    {
                        order.orderInfo.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                        orderinfos.AddRange(order.orderInfo);
                    }
                }
                else
                {
                    foreach (Tb_OrderBag order in orders)
                    {
                        order.orderInfo.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                        orderinfos.AddRange(order.orderInfo.Where(p => p.status == status));
                    }
                }
                orderinfos = orderinfos.OrderByDescending(p => p.OrderProductCode).ToList();
                List<OrderProductUser> products = OrderInfoChange(orderinfos);
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        public List<OrderProductUser> GetOrderInfoByTimeStoreProcedure(DateTime start, DateTime end, int status)
        {
            try
            {
                DataTable dt = new DataTable();
                DataTable dt2 = new DataTable();    //历史表中取
                if (status == -1 || status == (int)COM.OrderInfoStatus.Completed)                   //全部产品或已完成的产品列表需要从生产表和历史表中取
                {
                    dt = dll.GetOrderInfoByTimeStoreProcedure(start, end, status);
                    dt2 = dll.GetOrderInfoByTimeStoreProcedureBK(start, end, status);
                    foreach (DataRow r in dt2.Rows)
                    {
                        DataRow nr = dt.NewRow();
                        nr.ItemArray = r.ItemArray;
                        dt.Rows.Add(nr);
                    }
                }
                else
                {
                    dt = dll.GetOrderInfoByTimeStoreProcedure(start, end, status);
                }
                List<OrderProductUser> products = OrderInfoChangeDT(dt);
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 批量加急的产品
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="status"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public List<OrderProductUser> GetOrderInfoByTimeStoreProcedure2(DateTime start, DateTime end, int status, int priority)
        {
            try
            {
                DataTable dt = dll.GetOrderInfoByTimeStoreProcedure2(start, end, status, priority);
                List<OrderProductUser> products = OrderInfoChangeDT(dt);
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public enum OrderQueryStyle
        {
            DelyOne,
            DelyTwo,
            DelyMore,
            Stop,
            ShenHe,
            JiaJi

        }
        public int GetProductNum(int style)
        {
            string selectSql = "";
            int RtnInt = 0;
            DateTime stTime ;
            DateTime endTime ;
            switch (style)
            {
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyOne:
                    stTime = DateTime.Now.AddDays(-1).Date;
                    endTime = DateTime.Now.Date;
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and orderinfo.status=" + (int)OrderInfoStatus.Doing + " and OrderTime <"+endTime +" and ordertime>"+stTime;
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyTwo:
                    stTime = DateTime.Now.AddDays(-2).Date;
                    endTime = DateTime.Now.AddDays(-1).Date;
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and orderinfo.status=" + (int)OrderInfoStatus.Doing + " and OrderTime <" + endTime + " and ordertime>" + stTime;
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyMore:
                    stTime = DateTime.Now.AddDays(-3).Date;
                    endTime = DateTime.Now.AddDays(-1).Date;
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and orderinfo.status=" + (int)OrderInfoStatus.Doing + " and OrderTime <" + endTime ;
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.Stop:
                    //stTime = DateTime.Now.AddDays(-3).Date;
                    //endTime = DateTime.Now.AddDays(-1).Date;
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and orderinfo.status=" + (int)OrderInfoStatus.Stop ;
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.ShenHe:
                    //stTime = DateTime.Now.AddDays(-3).Date;
                    //endTime = DateTime.Now.AddDays(-1).Date;
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and (orderinfo.status=" + (int)OrderInfoStatus.WaitCheck + " ||orderinfo.status=" + (int)OrderInfoStatus.WaitPay+")";
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
                case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.JiaJi:
                    selectSql = "select count(*) from  orderinfo,tb_Tb_OrderBag where Tb_OrderBag.OrderBagId=orderinfo.OrderBagId and (orderinfo.status=" + (int)OrderInfoStatus.Doing + " and Priority>=10";
                    RtnInt = dll.GetProductNum(selectSql);
                    break;
            }
            return RtnInt;

        }

        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="noCondition"></param>
        /// <returns></returns>
        public List<OrderProductUser> FindOrderInfo(OrderInfoCondition condition, OrderInfoNoCondition noCondition)
        {
            try
            {
                List<orderInfo> resultInfos = new List<orderInfo>();
                List<orderInfo_BK> resultInfos_bk = new List<orderInfo_BK>();                               //备份
                //与产品相关的查询
                List<orderInfo> orderInfoConditions = new List<orderInfo>();
                List<orderInfo_BK> orderInfoConditions_bk = new List<orderInfo_BK>();                       //备份
                string con = string.Empty;
                string con_bk = string.Empty;
                if (condition.OrderProductCode.Length > 0)
                {
                    con += " and it.OrderProductCode like '%" + condition.OrderProductCode + "%'";
                }
                if (condition.CtmName.Length > 0)
                {
                    con += " and it.CtmName like '%" + condition.CtmName + "%'";
                }
                if (con.Length > 0)
                {
                    con = "where " + con.Substring(4);
                    orderInfoConditions = dll.GetOrderInfoCondition(con);
                    orderInfoConditions_bk = dll.GetOrderInfoCondition_bk(con);                             //备份  
                }

                //与产品不相关的查询(按照片查询)
                List<orderInfo> orderInfoNoConditions = new List<orderInfo>();
                List<orderInfo_BK> orderInfoNoConditions_bk = new List<orderInfo_BK>();                     //备份
                if (noCondition.PhotoCode.Length > 0)
                {
                    orderInfoNoConditions = dll.GetOrderInfoByPhotoCode(noCondition.PhotoCode);
                    orderInfoNoConditions_bk = dll.GetOrderInfoByPhotoCode_bk(noCondition.PhotoCode);       //备份
                }

                if (orderInfoConditions.Count > 0)
                {
                    if (orderInfoNoConditions.Count == 0)
                    {
                        resultInfos = orderInfoConditions;
                    }
                    else
                    {
                        foreach (orderInfo pInfo in orderInfoNoConditions)
                        {
                            if (orderInfoConditions.Contains(pInfo))
                            {
                                resultInfos.Add(pInfo);
                            }
                        }
                    }
                }
                else
                {
                    if (orderInfoNoConditions.Count == 0)
                    {
                        //return null;
                    }
                    else
                    {
                        resultInfos = orderInfoNoConditions;
                    }
                }

                //备份
                if (orderInfoConditions_bk.Count > 0)
                {
                    if (orderInfoNoConditions_bk.Count == 0)
                    {
                        resultInfos_bk = orderInfoConditions_bk;
                    }
                    else
                    {
                        foreach (orderInfo_BK pInfo in orderInfoNoConditions_bk)
                        {
                            if (orderInfoConditions_bk.Contains(pInfo))
                            {
                                resultInfos_bk.Add(pInfo);
                            }
                        }
                    }
                }
                else
                {
                    if (orderInfoNoConditions_bk.Count == 0)
                    {
                        //return null;
                    }
                    else
                    {
                        resultInfos_bk = orderInfoNoConditions_bk;
                    }
                }



                if (resultInfos.Count == 0 && resultInfos_bk.Count == 0)
                    return null;
                else
                {
                    resultInfos = resultInfos.OrderByDescending(p => p.OrderProductCode).ToList();
                    resultInfos_bk = resultInfos_bk.OrderByDescending(p => p.OrderProductCode).ToList();
                    //超过100条，只显示前100条
                    if (resultInfos.Count > 10000)
                        resultInfos.RemoveRange(100, resultInfos.Count - 10000);
                    if (resultInfos_bk.Count > 10000)
                    {
                        resultInfos_bk.RemoveRange(10000, resultInfos_bk.Count - 10000);
                    }
                    List<OrderProductUser> infos = new List<OrderProductUser>();
                    infos.AddRange(OrderInfoChange(resultInfos));
                    infos.AddRange(OrderInfoChange_bk(resultInfos_bk));
                    return infos;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 按照片编号查询(存储过程)
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="noCondition"></param>
        /// <returns></returns>
        public List<OrderProductUser> FindOrderInfoByPhotoCodeProcedure(string photoCode, DateTime start, DateTime end)
        {
            try
            {
                DataTable dt = dll.FindOrderInfoByPhotoCode(photoCode, start, end);
                DataTable dt2 = dll.FindOrderInfoByPhotoCode_bk(photoCode, start, end);
                foreach (DataRow r in dt2.Rows)
                {
                    DataRow nr = dt.NewRow();
                    nr.ItemArray = r.ItemArray;
                    dt.Rows.Add(nr);
                }
                return OrderInfoChangeDT(dt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 查询(存储过程)
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="noCondition"></param>
        /// <returns></returns>
        public List<OrderProductUser> FindOrderInfoProcedure(string productCode, string ctmName, string shopName, DateTime start, DateTime end)
        {
            try
            {
                DataTable dt = dll.FindOrderInfo(productCode, ctmName, shopName, start, end);
                DataTable dt2 = dll.FindOrderInfo_bk(productCode, ctmName, shopName, start, end);
                foreach (DataRow r in dt2.Rows)
                {
                    DataRow nr = dt.NewRow();
                    nr.ItemArray = r.ItemArray;
                    dt.Rows.Add(nr);
                }
                return OrderInfoChangeDT(dt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region orderInfo转化成OrderProductUser
        /// <summary>
        /// orderInfo转化成OrderProductUser
        /// </summary>
        /// <param name="orderInfos"></param>
        /// <returns></returns>
        private List<OrderProductUser> OrderInfoChange(List<orderInfo> orderInfos)
        {
            try
            {
                List<OrderProductUser> products = new List<OrderProductUser>();
                foreach (orderInfo info in orderInfos)
                {
                    OrderProductUser product = new OrderProductUser();
                    if (!info.Tb_OrderBagReference.IsLoaded)
                        info.Tb_OrderBagReference.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                    if (!info.Tb_OrderBag.ShopReference.IsLoaded)
                        info.Tb_OrderBag.ShopReference.Load();
                    if (!info.OutProcessRecord.IsLoaded)
                        info.OutProcessRecord.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                    product.ShopName = info.Tb_OrderBag.Shop.shopName;
                    product.CompletedTime = info.CompleteTime;
                    product.CtmName = info.CtmName;
                    List<string> techInfo = dll.GetOrderProductCurrentTech(info.OrderProductId);      //获取产品当前流程
                    if (techInfo.Count > 0)
                    {
                        product.CurrentTech = techInfo[0];
                        if (product.CurrentTech.Length > 0 && techInfo[1].Length > 0)
                            product.TechTime = Convert.ToDateTime(techInfo[1]);
                    }
                    else
                    {
                        product.CurrentTech = "完成";
                    }
                    product.Height = info.Height;
                    product.Width = info.Width;
                    product.OrderCode = info.Tb_OrderBag.BagCode;
                    product.OrderName = info.Tb_OrderBag.BagName;
                    product.OrderTime = info.Tb_OrderBag.OrderTime;
                    product.FetchTime = info.Tb_OrderBag.FetchTime;
                    product.OrderProductCode = info.OrderProductCode;
                    product.OrderProductId = info.OrderProductId;
                    product.OrderProductName = info.OrderProductName;
                    product.OrderProductPath = info.OrderPath;
                    product.Remark = info.Remark;
                    product.Status = info.status;
                    if (info.OutProcessRecord != null && info.OutProcessRecord.Count > 0)
                    {
                        if (!info.OutProcessRecord.First().OutProcessShopReference.IsLoaded)
                        {
                            info.OutProcessRecord.First().OutProcessShopReference.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                        }
                        product.OutShopName = info.OutProcessRecord.First().OutProcessShop.OutShopName;
                        product.OutShopStartProductTime = Convert.ToDateTime(info.OutProcessRecord.First().StartProductTime);
                    }
                    OrderInfoStatus os = (OrderInfoStatus)product.Status;
                    switch (os)
                    {
                        case OrderInfoStatus.WaitCheck:
                            product.StatusStr = "等待审核"; break;
                        case OrderInfoStatus.Doing:
                            product.StatusStr = "正在生产中"; break;
                        case OrderInfoStatus.Error:
                            product.StatusStr = "发生错误"; break;
                        case OrderInfoStatus.FenPianCompleted:
                            product.StatusStr = "分片完成"; break;
                        case OrderInfoStatus.OutProcess:
                            product.StatusStr = "委外加工中"; break;
                        case OrderInfoStatus.OverOrder:
                            product.StatusStr = "已结单"; break;
                        case OrderInfoStatus.Received:
                            product.StatusStr = "已收件"; break;
                        case OrderInfoStatus.Stop:
                            product.StatusStr = "停止生产"; break;
                        case OrderInfoStatus.Completed:
                            product.StatusStr = "完成"; break;
                        case OrderInfoStatus.NoCheckCount:
                        case OrderInfoStatus.WaitPay:
                            product.StatusStr = "余额不足"; break;
                        case OrderInfoStatus.WaitPhotoMove:
                        case OrderInfoStatus.WaitPayAndWaitMovePhoto:
                            product.StatusStr = "移动照片"; break;
                        case OrderInfoStatus.AutoOrderWait:
                            product.StatusStr = "远程开单等待审核"; break;
                        default: product.StatusStr = "未知状态"; break;
                    }
                    products.Add(product);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// orderInfo转化成OrderProductUser
        /// </summary>
        /// <param name="orderInfos"></param>
        /// <returns></returns>
        private List<OrderProductUser> OrderInfoChange_bk(List<orderInfo_BK> orderInfos)
        {
            try
            {
                List<OrderProductUser> products = new List<OrderProductUser>();
                foreach (orderInfo_BK info in orderInfos)
                {
                    OrderProductUser product = new OrderProductUser();
                    if (!info.Tb_OrderBag_BKReference.IsLoaded)
                        info.Tb_OrderBag_BKReference.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                    if (!info.Tb_OrderBag_BK.ShopReference.IsLoaded)
                        info.Tb_OrderBag_BK.ShopReference.Load();
                    if (!info.OutProcessRecord_BK.IsLoaded)
                        info.OutProcessRecord_BK.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                    product.ShopName = info.Tb_OrderBag_BK.Shop.shopName;
                    product.CompletedTime = info.CompleteTime;
                    product.CtmName = info.CtmName;
                    //List<string> techInfo = dll.GetOrderProductCurrentTech_bk(info.OrderProductId);      //获取产品当前流程(备份)
                    //if (techInfo.Count > 0)
                    //{
                    //    product.CurrentTech = techInfo[0];
                    //    if (product.CurrentTech.Length > 0)
                    //        product.TechTime = Convert.ToDateTime(techInfo[1]);
                    //}
                    //else
                    //{
                    //    product.CurrentTech = "完成";
                    //}
                    product.CurrentTech = "完成";
                    product.Height = info.Height;
                    product.Width = info.Width;
                    product.OrderCode = info.Tb_OrderBag_BK.BagCode;
                    product.OrderName = info.Tb_OrderBag_BK.BagName;
                    product.OrderTime = info.Tb_OrderBag_BK.OrderTime;
                    product.FetchTime = info.Tb_OrderBag_BK.FetchTime;
                    product.OrderProductCode = info.OrderProductCode;
                    product.OrderProductId = info.OrderProductId;
                    product.OrderProductName = info.OrderProductName;
                    product.OrderProductPath = info.OrderPath;
                    product.Remark = info.Remark;
                    product.Status = info.status;
                    if (info.OutProcessRecord_BK != null && info.OutProcessRecord_BK.Count > 0)
                    {
                        if (!info.OutProcessRecord_BK.First().OutProcessShopReference.IsLoaded)
                        {
                            info.OutProcessRecord_BK.First().OutProcessShopReference.Load(System.Data.Objects.MergeOption.OverwriteChanges);
                        }
                        product.OutShopName = info.OutProcessRecord_BK.First().OutProcessShop.OutShopName;
                        product.OutShopStartProductTime = Convert.ToDateTime(info.OutProcessRecord_BK.First().StartProductTime);
                    }
                    OrderInfoStatus os = (OrderInfoStatus)product.Status;
                    switch (os)
                    {
                        case OrderInfoStatus.WaitCheck:
                            product.StatusStr = "等待审核"; break;
                        case OrderInfoStatus.Doing:
                            product.StatusStr = "正在生产中"; break;
                        case OrderInfoStatus.Error:
                            product.StatusStr = "发生错误"; break;
                        case OrderInfoStatus.FenPianCompleted:
                            product.StatusStr = "分片完成"; break;
                        case OrderInfoStatus.OutProcess:
                            product.StatusStr = "委外加工中"; break;
                        case OrderInfoStatus.OverOrder:
                            product.StatusStr = "已结单"; break;
                        case OrderInfoStatus.Received:
                            product.StatusStr = "已收件"; break;
                        case OrderInfoStatus.Stop:
                            product.StatusStr = "停止生产"; break;
                        case OrderInfoStatus.Completed:
                            product.StatusStr = "完成"; break;
                        case OrderInfoStatus.NoCheckCount:
                        case OrderInfoStatus.WaitPay:
                            product.StatusStr = "余额不足"; break;
                        case OrderInfoStatus.WaitPhotoMove:
                            product.StatusStr = "移动照片"; break;
                        case OrderInfoStatus.WaitPayAndWaitMovePhoto:
                            product.StatusStr = "等待付款"; break;
                        case OrderInfoStatus.Deleted:
                            product.StatusStr = "删除"; break;
                        case OrderInfoStatus.AutoOrderWait:
                            product.StatusStr = "远程开单等待审核"; break;
                        default: product.StatusStr = "未知状态"; break;
                    }
                    products.Add(product);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private List<OrderProductUser> OrderInfoChangeDT(DataTable dt)
        {
            try
            {
                List<OrderProductUser> products = new List<OrderProductUser>();
                foreach (DataRow info in dt.Rows)
                {
                    OrderProductUser product = new OrderProductUser();
                    product.ShopName = info["ShopName"].ToString();
                    product.Area = info["Area"].ToString();
                    //if (info["BillCreateTime"] != DBNull.Value)
                    //    product.BillCreateTime = Convert.ToDateTime(info["BillCreateTime"]).ToString("yyyy-MM-dd HH:mm");
                    product.CompletedTime = Convert.ToDateTime(info["CompleteTime"]);
                    product.CtmName = info["CtmName"].ToString();
                    product.CurrentTech = info["TechName"].ToString();//获取产品当前流程
                    if (info["AssignTime"] != DBNull.Value)
                        product.TechTime = Convert.ToDateTime(info["AssignTime"]);
                    if (info["OutShopName"] != DBNull.Value)
                        product.OutShopName = info["OutShopName"].ToString();
                    if (info["OutShopStartProductTime"] != DBNull.Value)
                        product.OutShopStartProductTime = Convert.ToDateTime(info["OutShopStartProductTime"]);
                    product.Height = Convert.ToDouble(info["Height"]);
                    product.Width = Convert.ToDouble(info["Width"]);
                    product.OrderCode = info["BagCode"].ToString();
                    product.OrderName = info["BagName"].ToString();
                    product.OrderTime = Convert.ToDateTime(info["OrderTime"]);
                    product.FetchTime = Convert.ToDateTime(info["FetchTime"]);
                    product.OrderProductCode = info["OrderProductCode"].ToString();
                    product.OrderProductId = Convert.ToInt32(info["OrderProductId"]);
                    product.OrderProductName = info["OrderProductName"].ToString();
                    product.OrderProductPath = info["OrderPath"].ToString();
                    product.Remark = info["Remark"].ToString();
                    product.Status = Convert.ToInt16(info["status"]);
                    if (info["photoNum"] != DBNull.Value)
                        product.PhotoNum = Convert.ToInt32(info["photoNum"]);
                    else
                        product.PhotoNum = 0;
                    if (info["photoArea"] != DBNull.Value)
                        product.photoArea =Math.Round( Convert.ToDouble(info["photoArea"]),2);
                    else
                        product.photoArea=0;

                    if (info["Priority"] == DBNull.Value)
                        product.OrderProductPriority = 0;
                    else
                        product.OrderProductPriority = Convert.ToInt16(info["Priority"]);
                    product.StatusStr = GetInfoStatusStr(product.Status);
                    if (product.CurrentTech == null || product.CurrentTech.Length == 0)
                    {
                        if (product.StatusStr == "正在生产中")
                            product.CurrentTech = "无流程";
                        else
                            product.CurrentTech = "完成";
                    }
                    product.ProductCategoryName = info["ProductCategoryName"].ToString();
                    product.productNum = Convert.ToInt32(info["productNum"].ToString());
                    products.Add(product);
                }
                return products;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 产品的中文状态
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        private string GetInfoStatusStr(int status)
        {
            string statusStr = "";
            OrderInfoStatus os = (OrderInfoStatus)status;
            switch (os)
            {
                case OrderInfoStatus.WaitCheck:
                    statusStr = "等待审核"; break;
                case OrderInfoStatus.Doing:
                    statusStr = "正在生产中"; break;
                case OrderInfoStatus.Error:
                    statusStr = "发生错误"; break;
                case OrderInfoStatus.FenPianCompleted:
                    statusStr = "分片完成"; break;
                case OrderInfoStatus.OutProcess:
                    statusStr = "委外加工中"; break;
                case OrderInfoStatus.OverOrder:
                    statusStr = "已结单"; break;
                case OrderInfoStatus.Received:
                    statusStr = "已收件"; break;
                case OrderInfoStatus.Stop:
                    statusStr = "停止生产"; break;
                case OrderInfoStatus.Completed:
                    statusStr = "完成"; break;
                case OrderInfoStatus.NoCheckCount:
                case OrderInfoStatus.WaitPay:
                    statusStr = "余额不足"; break;
                case OrderInfoStatus.WaitPhotoMove:
                case OrderInfoStatus.WaitPayAndWaitMovePhoto:
                    statusStr = "移动照片"; break;
                case OrderInfoStatus.Deleted:
                    statusStr = "删除"; break;
                case OrderInfoStatus.AutoOrderWait:
                    statusStr = "远程开单等待审核"; break;
                default: statusStr = "未知状态"; break;
            }
            return statusStr;
        }
        private string GetFlowStatusStr(int status)
        {
            string statusStr = "";
            OrderFlowListStatus os = (OrderFlowListStatus)status;
            switch (os)
            {
                case OrderFlowListStatus.Complete:
                    statusStr = "完成"; break;
                case OrderFlowListStatus.Disable:
                    statusStr = "不可用"; break;
                case OrderFlowListStatus.Error:
                    statusStr = "错误"; break;
                case OrderFlowListStatus.UnProduct:
                    statusStr = "暂停生产"; break;
                case OrderFlowListStatus.Useable:
                    statusStr = "正在生产"; break;
                case OrderFlowListStatus.UseableAccept:
                    statusStr = "已接收"; break;
                case OrderFlowListStatus.Wait:
                    statusStr = "等待接收"; break;
            }
            return statusStr;
        }
       

        #region 加急
        /// <summary>
        /// 加急
        /// </summary>
        /// <param name="orderProductIds"></param>
        /// <param name="priority"></param>
        public void SetPriority(List<int> orderProductIds, int priority)
        {
            try
            {
                dll.SetPriority(orderProductIds, priority);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //------------------------------新增功能----------------------
        #region 根据产品Id取得订单Id
        /// <summary>
        /// 根据产品Id取得订单Id
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOrderBagIdByOrderProductId(int orderProductId)
        {
            try
            {
                return dll.GetOrderBagIdByOrderProductId(orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据产品Id取得其所属订单的状态
        /// <summary>
        /// 根据产品Id取得其所属订单的状态
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOrderStatusByOrderProductId(int orderProductId)
        {
            try
            {
                return dll.GetOrderStatusByOrderProductId(orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品内所有的照片
        /// <summary>
        /// 产品内所有的照片
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public DataTable GetPhotosByOrderProductId(int orderProductId, int orderStatus)
        {
            try
            {
                DataTable dt = new DataTable();
                if (orderStatus == (int)COM.OrderBagStatus.Completed)                   //订单已完成，从备份取
                {
                    dt = dll.GetPhotosByOrderProductId_bk(orderProductId);
                    if (dt.Rows.Count == 0)                                                //可能还未移动
                        dt = dll.GetPhotosByOrderProductId(orderProductId);
                }
                else
                {
                    dt = dll.GetPhotosByOrderProductId(orderProductId);
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品流程
        /// <summary>
        /// 产品流程
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public DataTable GetFlowByOrderProductId(int orderProductId, int orderStatus)
        {
            try
            {
                DataTable dt = null;
                if (orderStatus == (int)COM.OrderBagStatus.Completed)
                {
                    dt = dll.GetFlowByOrderProductId_bk(orderProductId);
                    if (dt == null || dt.Rows.Count == 0)
                        dt = dll.GetFlowByOrderProductId(orderProductId);
                }
                else
                {
                    dt = dll.GetFlowByOrderProductId(orderProductId);
                }
                foreach (DataRow r in dt.Rows)
                {
                    r["StatusStr"] = GetFlowStatusStr(Convert.ToInt32(r["Status"]));
                    int techtype =Convert.ToInt32( r["TechType"]);
                    int status = Convert.ToInt32(r["Status"]);
                    int userid = Convert.ToInt32(r["UserId"]);
                    if (techtype == (int)TechType.PrintBill && status == 1 && userid!=0)
                    {
                        r["UserName"] = "已扫描";
                    }
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品的停止，恢复记录
        /// <summary>
        /// 产品的停止，恢复记录
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public DataTable GetStopRecordByOrderProductId(int orderProductId)
        {
            try
            {
                DataTable dt = dll.GetStopRecordByOrderProductId(orderProductId);
                foreach (DataRow r in dt.Rows)
                {
                    int status = Convert.ToInt16(r["operatetype"]);
                    string statusStr = "";
                    switch (status)
                    {
                        case 0:
                            statusStr = "停止"; break;
                        case 1:
                            statusStr = "恢复"; break;
                    }
                    r["OrderProductStatus"] = statusStr;
                }
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //-------------------------数据结构------------------------

        #region 产品
        /// <summary>
        /// 产品
        /// </summary>
        public class OrderProductUser
        {
            public int OrderProductId { get; set; }
            public string Area { get; set; }
            public string ShopName { get; set; }
            public string OrderProductCode { get; set; }
            public string OrderProductName { get; set; }
            public string ProductName {
                get
                {
                    int lastIndex = OrderProductName.LastIndexOf('_');
                    if (!string.IsNullOrEmpty(OrderProductName) && lastIndex>0)
                    {
                        return OrderProductName.Substring(lastIndex+1);
                    }
                    else
                    {
                        return OrderProductName;
                    }
                }
            }
            public int OrderProductPriority { get; set; }
            public string OutShopName { get; set; }
            public DateTime OutShopStartProductTime { get; set; }       //委外商接收产品时间
            public string OrderCode { get; set; }
            public string OrderName { get; set; }
            public DateTime OrderTime { get; set; }
            public DateTime FetchTime { get; set; }                     //
            public string CtmName { get; set; }
            public DateTime CompletedTime { get; set; }             //?完成时间
            //public string BillCreateTime { get; set; }              //账单打印时间
            public int Status { get; set; }
            public string StatusStr { get; set; }
            public string OrderProductPath { get; set; }
            public double Width { get; set; }
            public double Height { get; set; }
            public string CurrentTech { get; set; }
            public DateTime TechTime { get; set; }                  //节点时间？(到底需要什么时间)
            public string Remark { get; set; }
            public int PhotoNum { get; set; }     //产品照片总张数
            public double photoArea { get; set; }//产品照片总面积
            public int productNum { get; set; }
            public string ProductCategoryName { get; set; }
        }
        #endregion

        #region 与产品相关的查询条件
        /// <summary>
        /// 与产品相关的查询条件
        /// </summary>
        public class OrderInfoCondition
        {
            public string OrderProductCode { get; set; }
            public string CtmName { get; set; }
        }
        #endregion

        #region 与产品不相关的查询条件
        /// <summary>
        /// 与产品不相关的查询条件
        /// </summary>
        public class OrderInfoNoCondition
        {
            public string PhotoCode { get; set; }
        }
        #endregion

        /// <summary>
        /// 将等待审核的产品改为可生产
        /// </summary>
        /// <param name="orderProductIds"></param>
        public void SetOrderProduct(List<int> orderProductIds)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var orderProductId in orderProductIds)
                {
                    orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                    if (oi != null)
                    {
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }
                        Tb_OrderBag obg = oi.Tb_OrderBag;

                        if (!obg.ShopReference.IsLoaded)
                        {
                            obg.ShopReference.Load();
                        }

                        obg.Shop.OrderBalance += oi.PrePriceCount;
                        oi.status = (int)OrderInfoStatus.Doing;

                        New_EmployeePerformance en = db.New_EmployeePerformance.FirstOrDefault(e => e.OrderproductId == orderProductId);
                        if (en != null)
                        {
                            en.Status = (int)OrderInfoStatus.Doing;
                        }
                    }
                }
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 试着将移动失败的图片再移动一次
        /// </summary>
        /// <param name="orderProductIds"></param>
        public void TryMovePhotoAgagin(List<int> orderProductIds)
        {
            if (orderProductIds.Count > 0)
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    foreach (var orderProductId in orderProductIds)
                    {
                        orderInfo oi = db.orderInfo.FirstOrDefault(o => o.OrderProductId == orderProductId);
                        if (oi != null)
                        {
                            if (!oi.photoInfo.IsLoaded)
                            {
                                oi.photoInfo.Load();
                            }
                            foreach (var pi in oi.photoInfo.ToList().Where(p => p.status == (int)PhotoStatus.PhotoNotExist).ToList())
                            {
                                pi.status = (int)PhotoStatus.WaitPhotoMove;
                            }
                        }
                    }

                    db.SaveChanges();
                }
            }
        }


        //扫描Code
        public OrderInfoProject ProjectSM(string orderCode, int OperateUid, out int gridid, out string mess)
        {
            gridid = 0;
            mess = "";
            OrderInfoProject oibll = new OrderInfoProject();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                string leftchar = orderCode.Substring(0, 1);
                orderInfo orinfo = new orderInfo();
                if (leftchar.Equals("2"))  //产品
                {
                    orinfo = db.orderInfo.FirstOrDefault(c => c.OrderProductCode == orderCode);
                }
                else if (leftchar.Equals("3")) //照片
                {
                    photoInfo photo = db.photoInfo.FirstOrDefault(c => c.PhotoBarCode == orderCode);
                    if (photo != null)
                    {
                        if (!photo.orderInfoReference.IsLoaded)
                        {
                            photo.orderInfoReference.Load();
                        }
                        orinfo = photo.orderInfo;
                    }
                    else
                    {
                        mess = "没有找到照片！";
                        return null;
                    }
                }

                if (orinfo == null || orinfo.OrderProductId == 0)
                {
                    mess = "没有找到产品！";
                    return null;
                }

                //获取当前产品正在生产的岗位
                tb_Tech tchmodel = new tb_Tech();
                WorkOrderFlowList wofl = db.WorkOrderFlowList.FirstOrDefault(s => s.orderInfo.OrderProductId == orinfo.OrderProductId && s.Status == 1);
                if (wofl == null || wofl.WorkFlowListId == 0)
                {
                    mess = "该编号不在生产中";
                    return oibll;
                }
                else
                {
                    if (!wofl.tb_TechReference.IsLoaded)
                    {
                        wofl.tb_TechReference.Load();
                    }
                    if (wofl.tb_Tech == null || wofl.tb_Tech.TechId == 0)
                    {
                        mess = "没有找到正在生产中的岗位";
                        return null;
                    }
                    if (wofl.tb_Tech.TechType !=(int)TechType.DigitalOutput)  //只能是合册岗位提交
                    {
                        mess = "不在合册岗位，不能提交";
                        return null;
                    }
                    tchmodel = wofl.tb_Tech;
                }

                //提交流程
                WorkFlowListBLL _wflBLL = new WorkFlowListBLL();
                bool retResult = _wflBLL.OverCurTech(tchmodel.TechId, OperateUid, orinfo.OrderProductId);
                if (!retResult)
                {
                    mess = "提交流程失败！";
                    return null;
                }

                //获取信息，更改格子存储信息
                if (!orinfo.Tb_OrderBagReference.IsLoaded)
                {
                    orinfo.Tb_OrderBagReference.Load();
                }
                Tb_OrderBag tb_odbag = db.Tb_OrderBag.FirstOrDefault(s => s.OrderBagId == orinfo.Tb_OrderBag.OrderBagId);
                if (!tb_odbag.ShopReference.IsLoaded)
                {
                    tb_odbag.ShopReference.Load();
                }
                Shop shop = db.Shop.FirstOrDefault(ss => ss.ShopId == tb_odbag.Shop.ShopId);
                GridSubArea gridarea = db.GridSubArea.FirstOrDefault(cc => cc.Type == 3);
                foreach (Grid item in db.Grid)
                {
                    if (!item.GridSubAreaReference.IsLoaded)
                    {
                        item.GridSubAreaReference.Load();
                    }
                }
                List<Grid> grid = db.Grid.Where(s => s.GridSubArea.SubAreaID == gridarea.SubAreaID).ToList();
                List<GridRecord> listgrid = db.GridRecord.ToList();
                foreach (GridRecord item in listgrid)
                {
                    if (!item.GridReference.IsLoaded)
                    {
                        item.GridReference.Load();
                    }
                }

                //所有合册格子
                List<GridRecord> listrecord = listgrid.Where(s => grid.Any(cc => cc.GridId == s.Grid.GridId)).ToList();
                //当前格子
                List<GridRecord> gridRecord = listrecord.Where(s => s.SomeId == orinfo.OrderProductId).ToList();
                //判断当前格子是否存在
                if (gridRecord.Count > 0)  //
                {
                    int id = gridRecord.FirstOrDefault().Grid.GridId;
                    gridid = id;
                    gridRecord.FirstOrDefault().Num++;
                    grid.FirstOrDefault(p => p.GridId == id).SomeId = orinfo.OrderProductId;
                    db.SaveChanges();
                }
                else//格子不存在是增加新格子
                {
                    GridRecord newrecord = new GridRecord();

                    List<GridRecord> ord = listrecord.Where(p => p.SomeId > 0).OrderBy(p => p.Grid.GridId).ToList(); //

                    List<Grid> newGridList = grid.Where(p => !ord.Any(cc => cc.Grid.GridId == p.GridId)).ToList();


                    Grid rid = newGridList.OrderBy(p => p.GridId).FirstOrDefault();
                    newrecord.Grid = rid;

                    newrecord.SomeId = orinfo.OrderProductId;
                    newrecord.CreateTime = DateTime.Now;
                    newrecord.Num = 1;
                    newrecord.OperateUid = OperateUid;
                    newrecord.Grid.Status = 1;
                    grid.FirstOrDefault(p => p.GridId == newrecord.Grid.GridId).SomeId = orinfo.OrderProductId;

                    gridid = newrecord.Grid.GridId;
                    db.SaveChanges();
                }
                oibll.shopName = shop.shopName;
                oibll.CtmName = orinfo.CtmName;
                oibll.orderName = orinfo.OrderProductName;
                oibll.orderCode = orinfo.OrderProductCode;
                if (gridRecord.Count == 0)
                {
                    oibll.Num = 1;
                }
                else
                {
                    oibll.Num = gridRecord.FirstOrDefault().Num;
                }

            }
            return oibll;
        }      
    }
}
